package com.ace.user.api.advice;

import com.ace.user.common.constant.R;
import com.alibaba.fastjson.JSON;
import com.ace.user.common.bean.RequestDTO;
import com.ace.user.common.bean.ResponseDTO;
import com.ace.user.common.http.BodyReaderHttpServletRequestWrapper;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.ServletInputStream;
import java.io.IOException;


/**
 * 处理返回值
 * 由于部分公共参数是请求携带的,响应需要返回
 * 这个类会提取请求部分参数,噻到响应参数中
 *
 * @Author yudong
 * @Date 2018年07月03日 上午11:10
 */
@Slf4j
@ControllerAdvice
public class ResponseBodyAdvice implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice {

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseDTO responseDTO = R.OK;
        try {
            ServletServerHttpRequest sshr = (ServletServerHttpRequest) request;
            BodyReaderHttpServletRequestWrapper httpServletRequest = (BodyReaderHttpServletRequestWrapper) sshr.getServletRequest();
            responseDTO.setData(body);
            ServletInputStream servletInputStream = httpServletRequest.getInputStream();
            RequestDTO requestDTO = JSON.parseObject(servletInputStream, RequestDTO.class);
            if (requestDTO != null) {
                responseDTO.setVersion(requestDTO.getVersion())
                        .setType(requestDTO.getType());
            }
            return responseDTO;
        } catch (IOException e) {
            e.printStackTrace();
            log.error(e.getLocalizedMessage());
        }
        return responseDTO;
    }
}
